/**
 * API接口模块
 * 提供应用所需的所有API接口
 */

// API基础URL
const BASE_URL = 'http://127.0.0.1:5002/api';

// 获取API端点URL
function getApiEndpoint() {
  return BASE_URL;
}

// 保持原有功能兼容
// 模拟数据存储
const storage = {
  glucose: [],
  bloodPressure: [],
  weight: []
};

// 原始的健康相关API实现
const health = {
  // 使用环境变量或配置决定是否使用真实API
  useRealApi: false, // 可根据环境变量或配置动态设置
  
  // 设置API模式
  setApiMode(useReal) {
    this.useRealApi = useReal;
    console.log(`[API] 健康数据API模式已设置为: ${useReal ? '真实API' : '模拟数据'}`);
  },
  
  // 获取记录
  async getRecords({ type, startDate, endDate, limit }) {
    console.log(`[API] 获取${type}记录`, { useRealApi: this.useRealApi });
    
    if (this.useRealApi) {
      // 基于类型调用相应的真实API
      switch(type.toLowerCase()) {
        case 'glucose':
          return realHealthApi.getGlucoseRecords({ startDate, endDate, limit })
            .then(res => res.success ? res.data.records : []);
        case 'bloodpressure':
          return realHealthApi.getBloodPressureRecords({ startDate, endDate, limit })
            .then(res => res.success ? res.data.records : []);
        case 'weight':
          return realHealthApi.getWeightRecords({ startDate, endDate, limit })
            .then(res => res.success ? res.data.records : []);
        default:
          console.error(`[API] 未知的健康数据类型: ${type}`);
          return [];
      }
    } else {
      // 使用原有的模拟数据逻辑
      return this._getRecordsSimulated({ type, startDate, endDate, limit });
    }
  },

  // 原有的模拟数据获取函数
  _getRecordsSimulated({ type, startDate, endDate, limit }) {
    console.log('API调用 getRecords 参数:', { type, startDate, endDate, limit });
    console.log('当前storage数据:', { 
      glucose: storage.glucose.length, 
      bloodPressure: storage.bloodPressure.length,
      weight: storage.weight.length
    });
    
    return new Promise((resolve) => {
      setTimeout(() => {
        // 确保type大小写一致，转换为小写
        const normalizedType = type ? type.toLowerCase() : '';
        let storageKey = normalizedType;
        
        // 处理类型名称的不一致
        if (normalizedType === 'bloodpressure') {
          storageKey = 'bloodPressure';
        }
        
        console.log('查询数据类型:', normalizedType, '映射到storage键:', storageKey);
        
        let records = storage[storageKey] || [];
        console.log('从storage获取原始数据, 数量:', records.length);
        
        // 如果有日期范围，进行过滤
        if (startDate && endDate) {
          const start = new Date(startDate).getTime();
          const end = new Date(endDate).getTime();
          records = records.filter(r => {
            const time = new Date(r.timestamp).getTime();
            return time >= start && time <= end;
          });
          console.log('日期过滤后的数据数量:', records.length);
        }

        // 限制返回数量
        if (limit) {
          records = records.slice(0, limit);
          console.log('限制数量后的数据:', records.length);
        }

        console.log('最终返回的数据量:', records.length);
        resolve(records);
      }, 200);
    });
  },

  // 添加记录
  async addRecord(type, data) {
    console.log(`[API] 添加${type}记录`, { useRealApi: this.useRealApi });
    
    if (this.useRealApi) {
      // 基于类型调用相应的真实API
      switch(type.toLowerCase()) {
        case 'glucose':
          return realHealthApi.addGlucoseRecord(data)
            .then(res => {
              if (res.success) {
                // 添加成功后刷新本地数据
                this._refreshLocalData(type);
              }
              return res.success;
            });
        case 'bloodpressure':
          return realHealthApi.addBloodPressureRecord(data)
            .then(res => {
              if (res.success) {
                this._refreshLocalData(type);
              }
              return res.success;
            });
        case 'weight':
          return realHealthApi.addWeightRecord(data)
            .then(res => {
              if (res.success) {
                this._refreshLocalData(type);
              }
              return res.success;
            });
        default:
          console.error(`[API] 未知的健康数据类型: ${type}`);
          return false;
      }
    } else {
      // 使用原有的模拟数据逻辑
      return this._addRecordSimulated(type, data);
    }
  },

  // 原有的模拟数据添加函数
  _addRecordSimulated(type, data) {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 确保数据格式正确
        const record = {
          ...data,
          timestamp: data.timestamp || new Date().toISOString(),
          _id: `sim_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        };
        
        // 添加到存储
        storage[type].unshift(record);
        if (storage[type].length > 100) {
          storage[type].pop();
        }
        
        // 保存到本地存储
        wx.setStorageSync(`health_${type}`, storage[type]);
        
        resolve(true);
      }, 200);
    });
  },

  // 刷新本地数据
  async _refreshLocalData(type) {
    try {
      const records = await this.getRecords({ type, limit: 100 });
      storage[type] = records;
      wx.setStorageSync(`health_${type}`, records);
    } catch (error) {
      console.error(`[API] 刷新${type}本地数据失败:`, error);
    }
  },

  // 初始化本地数据
  _initLocalData() {
    ['glucose', 'bloodPressure', 'weight'].forEach(type => {
      const savedData = wx.getStorageSync(`health_${type}`);
      if (savedData) {
        storage[type] = savedData;
      }
    });
  },

  // 删除记录
  async deleteRecord(type, timestamp) {
    console.log(`[API] 删除${type}记录`, { useRealApi: this.useRealApi, timestamp });
    
    if (this.useRealApi) {
      // 这里需要根据timestamp查找到对应的记录ID
      try {
        // 先获取所有记录，找到对应timestamp的记录
        const records = await this.getRecords({ type, limit: 1000 });
        
        // 更灵活的记录匹配 - 处理各种格式的时间戳
        let matchedRecord = null;
        const timestampNum = parseInt(timestamp);
        
        console.log(`[API] 正在从${records.length}条记录中查找timestamp: ${timestamp}`);
        
        for (const record of records) {
          // 检查各种可能的匹配情况
          if (record._id === timestamp) {
            matchedRecord = record;
            console.log(`[API] 通过ID匹配到记录:`, record);
            break;
          }
          
          // 检查timestamp字段 (数值比较)
          if (record.timestamp && parseInt(record.timestamp) === timestampNum) {
            matchedRecord = record;
            console.log(`[API] 通过timestamp数值匹配到记录:`, record);
            break;
          }
          
          // 检查measuredAt字段 (转换为毫秒时间戳比较)
          if (record.measuredAt) {
            const recordTime = new Date(record.measuredAt).getTime();
            if (recordTime === timestampNum) {
              matchedRecord = record;
              console.log(`[API] 通过measuredAt匹配到记录:`, record);
              break;
            }
            
            // 检查日期是否相同(不考虑时分秒)
            const recordDate = new Date(record.measuredAt).toDateString();
            const targetDate = new Date(timestampNum).toDateString();
            if (recordDate === targetDate) {
              matchedRecord = record;
              console.log(`[API] 通过日期匹配到记录:`, record);
              break;
            }
          }
        }
        
        if (!matchedRecord || !matchedRecord._id) {
          console.error(`[API] 未找到要删除的${type}记录, timestamp:`, timestamp);
          return false;
        }
        
        console.log(`[API] 找到记录，ID: ${matchedRecord._id}，准备删除`);
        
        // 基于类型调用相应的真实API
        switch(type.toLowerCase()) {
          case 'glucose':
            return realHealthApi.deleteGlucoseRecord(matchedRecord._id)
              .then(res => res.success);
          case 'bloodpressure':
            return realHealthApi.deleteBloodPressureRecord(matchedRecord._id)
              .then(res => res.success);
          case 'weight':
            return realHealthApi.deleteWeightRecord(matchedRecord._id)
              .then(res => res.success);
          default:
            console.error(`[API] 未知的健康数据类型: ${type}`);
            return false;
        }
      } catch (error) {
        console.error(`[API] 删除${type}记录失败:`, error);
        return false;
      }
    } else {
      // 使用原有的模拟数据逻辑
      return this._deleteRecordSimulated(type, timestamp);
    }
  },
  
  // 新增：批量删除记录
  /**
   * 批量删除健康记录
   * 支持一次性删除多条健康数据记录，提高删除效率
   * 适用于历史记录页面的"删除全部数据"功能
   * 
   * @param {string} type - 记录类型('glucose'、'bloodPressure'或'weight')
   * @param {Array} records - 要删除的记录数组
   * @returns {Promise<Object>} - 包含删除结果的对象，包括成功和失败的记录计数
   */
  async batchDeleteRecords(type, records) {
    console.log(`[API] 批量删除${type}记录`, { useRealApi: this.useRealApi, recordCount: records.length });
    
    if (this.useRealApi) {
      try {
        // 记录成功和失败的数量
        let successCount = 0;
        let failCount = 0;
        
        // 在真实API模式下，逐个调用删除API
        for (const record of records) {
          // 提取记录ID - 优先使用_id，然后是id，最后才使用timestamp
          const recordId = record._id || record.id || record.timestamp;
          
          try {
            let success = false;
            
            // 根据类型选择对应的API
            switch(type.toLowerCase()) {
              case 'glucose':
                success = await realHealthApi.deleteGlucoseRecord(recordId)
                  .then(res => res.success);
                break;
              case 'bloodpressure':
                success = await realHealthApi.deleteBloodPressureRecord(recordId)
                  .then(res => res.success);
                break;
              case 'weight':
                success = await realHealthApi.deleteWeightRecord(recordId)
                  .then(res => res.success);
                break;
              default:
                console.error(`[API] 未知的健康数据类型: ${type}`);
                success = false;
            }
            
            // 更新成功/失败计数器
            if (success) {
              successCount++;
            } else {
              failCount++;
            }
          } catch (err) {
            console.error(`[API] 删除记录失败:`, err);
            failCount++;
          }
        }
        
        // 删除操作完成后刷新本地数据
        await this._refreshLocalData(type);
        
        // 返回包含操作详情的结果对象
        return {
          success: true,
          successCount,
          failCount,
          total: records.length
        };
      } catch (error) {
        console.error(`[API] 批量删除记录失败:`, error);
        return {
          success: false,
          message: error.message || '删除失败',
          successCount: 0,
          failCount: records.length,
          total: records.length
        };
      }
    } else {
      // 使用模拟数据逻辑
      return this._batchDeleteRecordsSimulated(type, records);
    }
  },
  
  // 模拟数据的批量删除实现
  /**
   * 模拟数据模式下的批量删除实现
   * 从内存和本地存储中删除多条记录
   * 
   * @param {string} type - 记录类型('glucose'、'bloodPressure'或'weight')
   * @param {Array} records - 要删除的记录数组
   * @returns {Promise<Object>} - 包含删除结果的对象
   * @private
   */
  _batchDeleteRecordsSimulated(type, records) {
    return new Promise((resolve) => {
      setTimeout(() => {
        try {
          // 提取要删除记录的所有可能ID
          const recordIds = records.map(r => r._id || r.id || r.timestamp);
          const initialCount = storage[type].length;
          
          // 过滤掉要删除的记录
          storage[type] = storage[type].filter(r => {
            const recordId = r._id || r.id || r.timestamp;
            return !recordIds.includes(recordId);
          });
          
          // 计算成功删除的记录数量
          const deletedCount = initialCount - storage[type].length;
          
          // 保存更新后的数据到本地存储
          wx.setStorageSync(`health_${type}`, storage[type]);
          
          // 返回删除结果
          resolve({
            success: true,
            successCount: deletedCount,
            failCount: records.length - deletedCount,
            total: records.length
          });
        } catch (error) {
          console.error(`[API] 模拟批量删除失败:`, error);
          resolve({
            success: false,
            message: error.message || '删除失败',
            successCount: 0,
            failCount: records.length,
            total: records.length
          });
        }
      }, 200);
    });
  },
  
  // 原有的模拟数据删除函数
  _deleteRecordSimulated(type, timestamp) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const index = storage[type].findIndex(r => r.timestamp === timestamp);
        if (index > -1) {
          storage[type].splice(index, 1);
        }
        resolve(true);
      }, 200);
    });
  },
  
  // 更新记录
  async updateRecord(type, recordId, updatedData) {
    console.log(`[API] 更新${type}记录`, { useRealApi: this.useRealApi, recordId, updatedData });
    
    if (this.useRealApi) {
      // 这里需要根据recordId查找并更新记录
      try {
        // 基于类型调用相应的真实API
        switch(type.toLowerCase()) {
          case 'glucose':
            return realHealthApi.updateGlucoseRecord(recordId, updatedData)
              .then(res => {
                if (res.success) {
                  this._refreshLocalData(type);
                }
                return res.success;
              });
          case 'bloodpressure':
            return realHealthApi.updateBloodPressureRecord(recordId, updatedData)
              .then(res => {
                if (res.success) {
                  this._refreshLocalData(type);
                }
                return res.success;
              });
          case 'weight':
            return realHealthApi.updateWeightRecord(recordId, updatedData)
              .then(res => {
                if (res.success) {
                  this._refreshLocalData(type);
                }
                return res.success;
              });
          default:
            console.error(`[API] 未知的健康数据类型: ${type}`);
            return false;
        }
      } catch (error) {
        console.error(`[API] 更新${type}记录失败:`, error);
        return false;
      }
    } else {
      // 使用原有的模拟数据逻辑
      return this._updateRecordSimulated(type, recordId, updatedData);
    }
  },
  
  // 原有的模拟数据更新函数
  _updateRecordSimulated(type, recordId, updatedData) {
    console.log(`[API] 模拟更新${type}记录:`, { recordId, updatedData });
    
    return new Promise((resolve) => {
      setTimeout(() => {
        // 在模拟存储中找到对应的记录
        let found = false;
        const storageKey = type === 'bloodPressure' ? 'bloodPressure' : type;
        
        // 先检查是否使用ID查找
        if (recordId) {
          const recordIndex = storage[storageKey].findIndex(
            r => r._id === recordId || r.id === recordId
          );
          
          if (recordIndex !== -1) {
            // 保留原始ID，更新其他数据
            const originalId = storage[storageKey][recordIndex]._id || storage[storageKey][recordIndex].id;
            const originalTimestamp = storage[storageKey][recordIndex].timestamp;
            
            // 使用新数据，但保留原始ID
            storage[storageKey][recordIndex] = {
              ...updatedData,
              _id: originalId,
              id: originalId,
              timestamp: updatedData.timestamp || originalTimestamp
            };
            
            found = true;
            console.log(`[API] 通过ID ${recordId} 更新了${type}记录`);
          }
        }
        
        // 如果没有找到且有timestamp，尝试通过timestamp查找
        if (!found && updatedData.timestamp) {
          const recordIndex = storage[storageKey].findIndex(
            r => r.timestamp === updatedData.timestamp
          );
          
          if (recordIndex !== -1) {
            // 保留原始ID和时间戳
            const originalId = storage[storageKey][recordIndex]._id || storage[storageKey][recordIndex].id;
            
            // 更新记录
            storage[storageKey][recordIndex] = {
            ...updatedData,
              _id: originalId,
              id: originalId
            };
            
            found = true;
            console.log(`[API] 通过timestamp更新了${type}记录`);
          }
        }
        
        // 保存到本地存储
        wx.setStorageSync(`health_${storageKey}`, storage[storageKey]);
        
        resolve(found);
      }, 200);
    });
  },
  
  // 通过timestamp获取单条记录
  async getRecordByTimestamp(type, timestamp) {
    console.log(`[API] 通过timestamp获取${type}记录`, { useRealApi: this.useRealApi, timestamp });
    
    if (this.useRealApi) {
      // 对于真实API，我们需要先获取所有记录，然后过滤
      try {
        const records = await this.getRecords({ type, limit: 1000 });
        // 转换时间戳为数字以便比较
        const timestampNum = parseInt(timestamp);
        
        // 使用与deleteRecord相同的匹配逻辑
        for (const record of records) {
          // 直接ID匹配
          if (record._id === timestamp) {
            return record;
          }
          
          // timestamp字段数值比较
          if (record.timestamp && parseInt(record.timestamp) === timestampNum) {
            return record;
          }
          
          // measuredAt字段转换后比较
          if (record.measuredAt) {
            const recordTime = new Date(record.measuredAt).getTime();
            if (recordTime === timestampNum) {
              return record;
            }
          }
        }
        
        // 未找到匹配记录
        console.log(`[API] 未找到匹配的${type}记录, timestamp:`, timestamp);
        return null;
      } catch (error) {
        console.error(`[API] 获取${type}记录失败:`, error);
        return null;
      }
    } else {
      // 使用原有的模拟数据逻辑
      return this._getRecordByTimestampSimulated(type, timestamp);
    }
  },
  
  // 原有的模拟数据获取单条记录函数
  _getRecordByTimestampSimulated(type, timestamp) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const record = storage[type].find(r => r.timestamp === timestamp);
        resolve(record || null);
      }, 200);
    });
  },
  
  // 通过id获取单条记录
  async getRecord(type, id) {
    console.log(`[API] 通过id获取${type}记录`, { useRealApi: this.useRealApi, id });
    
    if (this.useRealApi) {
      // 根据类型调用对应的API
      try {
        switch(type.toLowerCase()) {
          case 'glucose':
            return realHealthApi.getGlucoseRecord(id)
              .then(res => res.success ? res.data : null);
          case 'bloodpressure':
            return realHealthApi.getBloodPressureRecord(id)
              .then(res => res.success ? res.data : null);
          case 'weight':
            return realHealthApi.getWeightRecord(id)
              .then(res => res.success ? res.data : null);
          default:
            console.error(`[API] 未知的健康数据类型: ${type}`);
            return null;
        }
      } catch (error) {
        console.error(`[API] 获取${type}记录失败:`, error);
        return null;
      }
    } else {
      // 使用原有的模拟数据逻辑
      return this._getRecordSimulated(type, id);
    }
  },
  
  // 原有的模拟数据获取单条记录函数
  _getRecordSimulated(type, id) {
    console.log('API调用 getRecord, 参数:', { type, id });
    return new Promise((resolve) => {
      setTimeout(() => {
        // 这里id实际上就是timestamp，但保持接口一致性
        const record = storage[type].find(r => r.timestamp === Number(id));
        console.log('查找结果:', record);
        resolve(record || null);
      }, 200);
    });
  },

  async getUserProfile() {
    try {
      const response = await request({
        url: '/users/profile',
        method: 'GET'
      });
      console.log('获取用户资料原始响应:', response);
      
      // 确保返回正确的数据结构
      if (response && response.success) {
        return {
          success: true,
          data: response.data || {}
        };
      } else {
        throw new Error(response?.message || '获取用户资料失败');
      }
    } catch (error) {
      console.error('获取用户资料失败:', error);
      throw error;
    }
  }
};

// 用户API
const user = {
  async getUserInfo() {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 返回模拟数据
        const userInfo = {
          nickname: '测试用户',
          avatar: '/images/avatar/default.png',
          gender: '男',
          age: 35,
          height: 170, // 身高(cm)
          weight: 68,  // 当前体重(kg)
          targetWeight: 65, // 目标体重(kg)
          diabetesRisk: 'low', // 糖尿病风险
          bloodSugarTarget: {
            before: { min: 3.9, max: 7.2 },
            after: { min: 3.9, max: 10.0 }
          }
        };
        resolve(userInfo);
      }, 200);
    });
  },

  async updateUserInfo(userInfo) {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟更新用户信息
        resolve(true);
      }, 200);
    });
  },

  async logout() {
    console.log('[API] 用户退出登录');
    wx.removeStorageSync('token');
    return Promise.resolve({ success: true });
  }
};

// 添加测试数据 - 该函数不应在生产环境中被频繁调用，会导致数据重置
// 现在统一使用utils/api/health.js中的initializeData函数
function addTestData() {
  console.log('[旧API] 注意: 此函数已废弃，使用了旧版测试数据初始化');
  console.log('[旧API] 开始添加测试数据');
  const now = new Date();
  now.setHours(23, 59, 59, 999);  // 设置为今天结束
  const day = 24 * 60 * 60 * 1000;
  
  // 清空现有数据
  storage.glucose = [];
  storage.bloodPressure = [];
  storage.weight = [];
  
  console.log('[旧API] 已清空现有数据，开始生成新数据');
  
  // 生成最近30天的数据
  for (let i = 0; i < 30; i++) {
    const date = new Date(now - i * day);
    
    // 早上数据 (8:00)
    date.setHours(8, 0, 0, 0);
    
    // 血糖数据
    storage.glucose.push({
      timestamp: date.getTime(),
      value: (Math.random() * 3 + 5).toFixed(1),
      period: 'morning'
    });
    
    // 添加血压数据 (8:00)
    storage.bloodPressure.push({
      timestamp: date.getTime(),
      systolic: Math.floor(Math.random() * 30 + 110),  // 收缩压范围110-140
      diastolic: Math.floor(Math.random() * 20 + 70),  // 舒张压范围70-90
      period: 'morning'
    });
    
    // 添加体重数据 (8:00) - 每天早上测量一次
    storage.weight.push({
      timestamp: date.getTime(),
      value: parseFloat((Math.random() * 10 + 60).toFixed(1)),  // 体重范围60-70kg，转换为数值类型
      note: ''
    });

    // 中午数据 (12:00)
    date.setHours(12, 0, 0, 0);
    
    // 血糖数据
    storage.glucose.push({
      timestamp: date.getTime(),
      value: (Math.random() * 3 + 5).toFixed(1),
      period: 'noon'
    });
    
    // 添加血压数据 (12:00)
    storage.bloodPressure.push({
      timestamp: date.getTime(),
      systolic: Math.floor(Math.random() * 30 + 110),
      diastolic: Math.floor(Math.random() * 20 + 70),
      period: 'noon'
    });

    // 晚上数据 (18:00)
    date.setHours(18, 0, 0, 0);
    
    // 血糖数据
    storage.glucose.push({
      timestamp: date.getTime(),
      value: (Math.random() * 3 + 5).toFixed(1),
      period: 'evening'
    });
    
    // 添加血压数据 (18:00)
    storage.bloodPressure.push({
      timestamp: date.getTime(),
      systolic: Math.floor(Math.random() * 30 + 110),
      diastolic: Math.floor(Math.random() * 20 + 70),
      period: 'evening'
    });
  }
  
  console.log('测试数据添加完成，总计数据量:', {
    glucose: storage.glucose.length,
    bloodPressure: storage.bloodPressure.length,
    weight: storage.weight.length
  });
}

// 初始化测试数据
addTestData();

// 初始化后打印数据总量
console.log('API初始化完成，总计数据量:', {
  glucose: storage.glucose.length,
  bloodPressure: storage.bloodPressure.length,
  weight: storage.weight.length
});

// 新版API引用
let newAPI = null;

// 获取新版API实例
function getNewAPI() {
  if (!newAPI) {
    try {
      newAPI = require('./api/index');
    } catch (err) {
      console.error('加载新版API失败:', err);
    }
  }
  return newAPI;
}

// 导入真实API请求函数
const { request, wxLogin } = require('./request.js');

// 用户相关API
const userAPI = {
  // 微信登录
  wxLoginAPI: async () => {
    console.log('开始处理微信登录请求');
    try {
      const { code, userInfo } = await wxLogin();
      console.log('获取到微信登录code:', code);
      console.log('用户信息:', userInfo);
      
      // 构建请求体
      const data = {
        code: code,
        ...(userInfo ? {
          nickname: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          gender: userInfo.gender,
          country: userInfo.country,
          province: userInfo.province,
          city: userInfo.city
        } : {})
      };
      
      console.log('发送到后端的微信登录数据:', data);
      
      const response = await request(`${BASE_URL}/users/wx-login`, 'POST', data);
      console.log('微信登录成功, 服务器返回数据:', response);
      
      // 存储用户Token
      if (response.token) {
        try {
          wx.setStorageSync('token', response.token);
          console.log('Token已保存到本地存储');
        } catch (e) {
          console.error('保存Token失败:', e);
        }
      }
      
      // 返回用户信息和登录状态
      return {
        success: true,
        user: response.user,
        isProfileComplete: response.user?.isProfileComplete || false,
        token: response.token
      };
    } catch (error) {
      console.error('微信登录失败:', error);
      return {
        success: false,
        error: error.message || '登录失败，请稍后再试'
      };
    }
  },
  
  // 获取用户信息
  getCurrentUser: async () => {
    try {
      const response = await request(`${BASE_URL}/users/me`, 'GET');
      console.log('获取当前用户信息成功:', response);
      return response;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      throw error;
    }
  },

  // 获取用户资料
  getUserProfile: async () => {
    try {
      const response = await request({
        url: '/users/profile',
        method: 'GET'
      });
      console.log('获取用户资料原始响应:', response);
      
      // 确保返回正确的数据结构
      if (response && response.success) {
        return {
          success: true,
          data: response.data || {}
        };
      } else {
        throw new Error(response?.message || '获取用户资料失败');
      }
    } catch (error) {
      console.error('获取用户资料失败:', error);
      throw error;
    }
  },
  
  // 更新用户健康档案
  updateHealthProfile: async (data) => {
    try {
      const response = await request(`${BASE_URL}/users/health-profile`, 'PUT', data);
      console.log('更新健康档案成功:', response);
      return response;
    } catch (error) {
      console.error('更新健康档案失败:', error);
      throw error;
    }
  },
  
  // 更新用户个人信息
  updateUserProfile: async (data) => {
    try {
      const response = await request(`${BASE_URL}/users/profile`, 'PUT', data);
      console.log('更新用户资料成功:', response);
      return response;
    } catch (error) {
      console.error('更新用户资料失败:', error);
      throw error;
    }
  }
};

// 实用函数：过滤掉undefined值
function cleanParams(params) {
  const cleanedParams = {};
  Object.keys(params).forEach(key => {
    if (params[key] !== undefined && params[key] !== 'undefined') {
      cleanedParams[key] = params[key];
    }
  });
  return cleanedParams;
}

// 确保日期字段格式正确
/**
 * 确保日期字段的格式正确，适合API使用
 * @param {string|Date} dateValue - 日期值，可以是ISO字符串或Date对象
 * @returns {string} - 格式化的ISO日期字符串
 */
function ensureValidDateFormat(dateValue) {
  try {
    // 如果已经是Date对象
    if (dateValue instanceof Date) {
      return dateValue.toISOString();
    }
    
    // 如果是字符串或数值，尝试转换为Date
    if (typeof dateValue === 'string' || typeof dateValue === 'number') {
      const date = new Date(dateValue);
      // 检查是否是有效日期
      if (!isNaN(date.getTime())) {
        // 转换为ISO格式返回
        return date.toISOString();
      }
    }
    
    // 如果转换失败，返回当前时间
    console.warn('[Date Format] 无效的日期值:', dateValue, '使用当前时间作为替代');
    return new Date().toISOString();
  } catch (e) {
    console.error('[Date Format] 日期格式化失败:', e);
    return new Date().toISOString();
  }
}

// 提醒相关API
const reminderApi = {
  // 获取提醒列表
  getReminders: async (type, enabled) => {
    const params = {};
    if (type) params.type = type;
    if (enabled !== undefined) params.enabled = enabled;
    
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&');
    
    const url = queryString ? `/reminders?${queryString}` : '/reminders';
    return request({
      url: url,
      method: 'GET'
    });
  },
  
  // 获取今日提醒
  getTodayReminders: async () => {
    return request({
      url: '/reminders/today',
      method: 'GET'
    });
  },
  
  // 获取即将到来的提醒
  getUpcomingReminders: async (limit = 5) => {
    return request({
      url: `/reminders/upcoming?limit=${limit}`,
      method: 'GET'
    });
  },
  
  // 获取提醒统计信息
  getReminderStats: async () => {
    return request({
      url: '/reminders/stats',
      method: 'GET'
    });
  },
  
  // 获取提醒类型列表
  getReminderTypes: async () => {
    return request({
      url: '/reminders/types',
      method: 'GET'
    });
  },
  
  // 获取单个提醒详情
  getReminderById: async (id) => {
    return request({
      url: `/reminders/${id}`,
      method: 'GET'
    });
  },
  
  // 创建新提醒
  createReminder: async (reminderData) => {
    return request({
      url: '/reminders',
      method: 'POST',
      data: reminderData
    });
  },
  
  // 更新提醒
  updateReminder: async (id, updateData) => {
    return request({
      url: `/reminders/${id}`,
      method: 'PUT',
      data: updateData
    });
  },
  
  // 删除提醒
  deleteReminder: async (id) => {
    return request({
      url: `/reminders/${id}`,
      method: 'DELETE'
    });
  },
  
  // 标记提醒为已完成
  completeReminder: async (id) => {
    return request({
      url: `/reminders/${id}/complete`,
      method: 'POST'
    });
  },
  
  // 延迟提醒
  snoozeReminder: async (id, minutes) => {
    return request({
      url: `/reminders/${id}/snooze`,
      method: 'POST',
      data: { minutes }
    });
  }
};

// 真实API健康数据接口
const realHealthApi = {
  // 获取血糖记录
  async getGlucoseRecords(params = {}) {
    return request({
      url: '/health/glucose',
      method: 'GET',
      data: cleanParams(params)
    });
  },
  
  // 添加血糖记录
  async addGlucoseRecord(data) {
    // 详细记录输入数据
    console.log('[API] 原始血糖记录数据:', JSON.stringify(data));
    console.log('[API] measuredAt字段:', data.measuredAt);
    console.log('[API] timestamp字段:', data.timestamp);
    
    // 确保日期字段格式有效
    let measuredAtValue;
    if (data.measuredAt) {
      measuredAtValue = ensureValidDateFormat(data.measuredAt);
      console.log('[API] 格式化后的measuredAt:', measuredAtValue);
    } else if (data.timestamp) {
      measuredAtValue = ensureValidDateFormat(data.timestamp);
      console.log('[API] 格式化后的timestamp:', measuredAtValue);
    } else {
      measuredAtValue = new Date().toISOString();
      console.log('[API] 使用当前时间:', measuredAtValue);
    }
    
    // 如果measuredAt是字符串，解析查看
    if (typeof data.measuredAt === 'string') {
      try {
        const parsedDate = new Date(data.measuredAt);
        console.log('[API] 解析measuredAt后的日期:', parsedDate.toISOString());
        console.log('[API] 解析measuredAt后的日期本地字符串:', parsedDate.toLocaleString());
      } catch (e) {
        console.error('[API] 解析measuredAt日期失败:', e);
      }
    }
    
    // 转换为后端期望的格式
    const apiData = {
      value: parseFloat(data.value), // 确保是数字
      measuredAt: measuredAtValue, // 使用格式化后的日期值
      category: data.period || '随机', // 测量时段
      notes: data.note || '', // 备注
      unit: 'mmol/L', // 单位
      isManualEntry: true // 手动录入
    };
    
    console.log('[API] 转换后的血糖记录数据:', JSON.stringify(apiData));
    console.log('[API] 最终使用的measuredAt:', apiData.measuredAt);
    console.log('[API] 最终解析后的日期:', new Date(apiData.measuredAt).toLocaleString());
    
    // 发送请求
    try {
      const response = await request({
        url: '/health/glucose',
        method: 'POST',
        data: apiData
      });
      
      console.log('[API] 添加血糖记录响应:', JSON.stringify(response));
      return response;
    } catch (error) {
      console.error('[API] 添加血糖记录失败:', error);
      throw error;
    }
  },
  
  // 获取单条血糖记录
  async getGlucoseRecord(id) {
    return request({
      url: `/health/glucose/${id}`,
      method: 'GET'
    });
  },
  
  // 更新血糖记录
  async updateGlucoseRecord(id, data) {
    return request({
      url: `/health/glucose/${id}`,
      method: 'PUT',
      data
    });
  },
  
  // 删除血糖记录
  async deleteGlucoseRecord(id) {
    return request({
      url: `/health/glucose/${id}`,
      method: 'DELETE'
    });
  },
  
  // 获取血糖统计数据
  async getGlucoseStats(params = {}) {
    return request({
      url: '/health/glucose/stats',
      method: 'GET',
      data: cleanParams(params)
    });
  },
  
  // 获取血压记录
  async getBloodPressureRecords(params = {}) {
    return request({
      url: '/health/blood-pressure',
      method: 'GET',
      data: cleanParams(params)
    });
  },
  
  // 添加血压记录
  async addBloodPressureRecord(data) {
    return request({
      url: '/health/blood-pressure',
      method: 'POST',
      data
    });
  },
  
  // 获取单条血压记录
  async getBloodPressureRecord(id) {
    return request({
      url: `/health/blood-pressure/${id}`,
      method: 'GET'
    });
  },
  
  // 更新血压记录
  async updateBloodPressureRecord(id, data) {
    return request({
      url: `/health/blood-pressure/${id}`,
      method: 'PUT',
      data
    });
  },
  
  // 删除血压记录
  async deleteBloodPressureRecord(id) {
    return request({
      url: `/health/blood-pressure/${id}`,
      method: 'DELETE'
    });
  },
  
  // 获取体重记录
  async getWeightRecords(params = {}) {
    return request({
      url: '/health/weight',
      method: 'GET',
      data: cleanParams(params)
    });
  },
  
  // 添加体重记录
  async addWeightRecord(data) {
    return request({
      url: '/health/weight',
      method: 'POST',
      data
    });
  },
  
  // 获取单条体重记录
  async getWeightRecord(id) {
    return request({
      url: `/health/weight/${id}`,
      method: 'GET'
    });
  },
  
  // 更新体重记录
  async updateWeightRecord(id, data) {
    return request({
      url: `/health/weight/${id}`,
      method: 'PUT',
      data
    });
  },
  
  // 删除体重记录
  async deleteWeightRecord(id) {
    return request({
      url: `/health/weight/${id}`,
      method: 'DELETE'
    });
  }
};

// 测试数据库连接
function testDatabaseConnection() {
  return request({
    url: `/test/db-connection`,
    method: 'GET',
    auth: false // 不需要认证
  }).then(res => {
    return res;
  }).catch(err => {
    console.error('[API] 测试数据库连接出错:', err);
    return {
      success: false,
      message: err.message || '连接服务器失败'
    };
  });
}

// 添加饮食相关API
const diet = {
  // 获取今日餐食
  async getTodayMeals() {
    const today = new Date().toISOString().split('T')[0];
    return request({
      url: `/diet/meals?date=${today}`,
      method: 'GET'
    });
  },
  
  // 获取指定日期餐食
  async getMealsByDate(date) {
    return request({
      url: `/diet/meals?date=${date}`,
      method: 'GET'
    });
  },
  
  // 获取餐食详情
  async getMealById(id) {
    return request({
      url: `/diet/meals/${id}`,
      method: 'GET'
    });
  },
  
  // 添加餐食记录
  async addMeal(mealData) {
    return request({
      url: '/diet/meals',
      method: 'POST',
      data: mealData
    });
  },
  
  // 修改餐食记录
  async updateMeal(id, mealData) {
    return request({
      url: `/diet/meals/${id}`,
      method: 'PUT',
      data: mealData
    });
  },
  
  // 删除餐食记录
  async deleteMeal(id) {
    return request({
      url: `/diet/meals/${id}`,
      method: 'DELETE'
    });
  },
  
  // 获取营养摄入统计
  async getNutritionStats(dateRange) {
    const query = dateRange ? `?startDate=${dateRange.start}&endDate=${dateRange.end}` : '';
    return request({
      url: `/diet/stats${query}`,
      method: 'GET'
    });
  },
  
  // 搜索食物
  async searchFoods(keyword, category) {
    let query = `?query=${encodeURIComponent(keyword || '')}`;
    if (category) {
      query += `&category=${encodeURIComponent(category)}`;
    }
    return request({
      url: `/diet/foods/search${query}`,
      method: 'GET'
    });
  },
  
  // 使用天行API搜索食物营养信息
  async searchTianapiFood(query, mode = 0, num = 10, page = 1) {
    // 不使用URLSearchParams(微信小程序不支持)，手动构建查询字符串
    const queryString = `query=${encodeURIComponent(query || '')}&mode=${mode}&num=${num}&page=${page}`;
    
    return request({
      url: `/diet/foods/tianapi/search?${queryString}`,
      method: 'GET'
    });
  },
  
  // 保存天行API返回的食物到数据库
  async saveTianapiFood(foodData) {
    // 确保数据完整性检查
    if (!foodData || !foodData.name) {
      console.error('保存食物失败: 食物数据不完整');
      return {
        success: false,
        message: '食物数据不完整'
      };
    }
    
    return request({
      url: '/diet/foods/tianapi/save',
      method: 'POST',
      data: { foodData }
    });
  },
  
  // 获取推荐食物
  async getRecommendedFoods(mealType, category) {
    let query = '?';
    if (mealType) {
      query += `mealType=${encodeURIComponent(mealType)}&`;
    }
    if (category) {
      query += `category=${encodeURIComponent(category)}`;
    }
    return request({
      url: `/diet/foods/recommended${query}`,
      method: 'GET'
    });
  },
  
  // 获取食物详情
  async getFoodById(id) {
    return request({
      url: `/diet/foods/${id}`,
      method: 'GET'
    });
  },
  
  // 添加自定义食物
  async addCustomFood(foodData) {
    return request({
      url: '/diet/foods',
      method: 'POST',
      data: foodData
    });
  },
  
  // 获取食物分类
  async getFoodCategories() {
    return request({
      url: '/diet/foods/categories',
      method: 'GET'
    });
  }
};

// 设备管理API
const deviceApi = {
  // 获取用户设备列表
  async getDevices(type = null) {
    try {
      // 修正URL构建方式，不直接使用BASE_URL拼接
      let url = '/devices';
      if (type) {
        url += `?type=${type}`;
      }
      console.log('请求设备列表URL:', url);
      const response = await request({
        url: url,
        method: 'GET'
      });
      console.log('获取设备列表成功:', response);
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('获取设备列表失败:', error);
      return {
        success: false,
        message: error.message || '获取设备列表失败'
      };
    }
  },

  // 获取单个设备详情
  async getDeviceById(id) {
    try {
      const url = `/devices/${id}`;
      console.log('请求设备详情URL:', url);
      const response = await request({
        url: url,
        method: 'GET'
      });
      console.log('获取设备详情成功:', response);
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('获取设备详情失败:', error);
      return {
        success: false,
        message: error.message || '获取设备详情失败'
      };
    }
  },

  // 添加设备
  async addDevice(deviceData) {
    try {
      const response = await request({
        url: '/devices',
        method: 'POST',
        data: deviceData
      });
      console.log('添加设备成功:', response);
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('添加设备失败:', error);
      return {
        success: false,
        message: error.message || '添加设备失败'
      };
    }
  },

  // 更新设备信息
  async updateDevice(id, updateData) {
    try {
      const response = await request({
        url: `/devices/${id}`,
        method: 'PUT',
        data: updateData
      });
      console.log('更新设备成功:', response);
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('更新设备失败:', error);
      return {
        success: false,
        message: error.message || '更新设备失败'
      };
    }
  },

  // 删除设备
  async deleteDevice(id) {
    try {
      const response = await request({
        url: `/devices/${id}`,
        method: 'DELETE'
      });
      console.log('删除设备成功:', response);
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('删除设备失败:', error);
      return {
        success: false,
        message: error.message || '删除设备失败'
      };
    }
  },

  // 更新设备同步时间
  async updateDeviceSync(id) {
    try {
      const response = await request({
        url: `/devices/${id}/sync`,
        method: 'PUT'
      });
      console.log('更新设备同步时间成功:', response);
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('更新设备同步时间失败:', error);
      return {
        success: false,
        message: error.message || '更新设备同步时间失败'
      };
    }
  }
};

// 健康知识相关API
const healthKnowledge = {
  // 获取随机健康知识
  getRandomKnowledge: async (count = 1, category = '') => {
    try {
      let url = `/health-knowledge/random?count=${count}`;
      if (category) url += `&category=${encodeURIComponent(category)}`;
      
      const response = await request({
        url: url,
        method: 'GET'
      });
      return response;
    } catch (error) {
      console.error('获取随机健康知识失败:', error);
      return [];
    }
  },
  
  // 获取健康知识列表
  getKnowledgeList: async (page = 1, limit = 10, category = '', tag = '', search = '', recommended = false) => {
    try {
      let url = `/health-knowledge?page=${page}&limit=${limit}`;
      if (category) url += `&category=${encodeURIComponent(category)}`;
      if (tag) url += `&tag=${encodeURIComponent(tag)}`;
      if (search) url += `&search=${encodeURIComponent(search)}`;
      if (recommended) url += '&recommended=true';
      
      const response = await request({
        url: url,
        method: 'GET'
      });
      return response;
    } catch (error) {
      console.error('获取健康知识列表失败:', error);
      return { data: [], pagination: { total: 0, page: 1, limit: 10, pages: 0 } };
    }
  },
  
  // 获取健康知识详情
  getKnowledgeById: async (id, noIncrement = false) => {
    try {
      let url = `/health-knowledge/${id}`;
      if (noIncrement) url += '?noIncrement=true';
      
      const response = await request({
        url: url,
        method: 'GET'
      });
      return response;
    } catch (error) {
      console.error('获取健康知识详情失败:', error);
      throw error;
    }
  },
  
  // 点赞健康知识
  likeKnowledge: async (id) => {
    try {
      const response = await request({
        url: `/health-knowledge/${id}/like`,
        method: 'PUT'
      });
      return response;
    } catch (error) {
      console.error('点赞健康知识失败:', error);
      throw error;
    }
  }
};

// 导出所有API函数
module.exports = {
  health,
  user,
  getApiEndpoint,
  testDatabaseConnection,
  // 提醒系统API
  reminder: reminderApi,
  // 导出用于微信登录的函数
  wxLogin,
  // 用户资料相关API
  getUserProfile: health.getUserProfile,
  // 新版API动态获取
  get configure() {
    const api = getNewAPI();
    return api ? api.configure : () => {};
  },
  
  get request() {
    const api = getNewAPI();
    return api ? api.request : null;
  },
  
  get medicalHistory() {
    const api = getNewAPI();
    return api ? api.medicalHistory : null;
  },
  
  get healthTarget() {
    const api = getNewAPI();
    return api ? api.healthTarget : null;
  },
  
  get riskAssessment() {
    const api = getNewAPI();
    return api ? api.riskAssessment : null;
  },
  
  // 用户相关API
  userAPI,
  diet,
  device: deviceApi,
  healthKnowledge
};
